// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
const _ = db.command

exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  let {
    op,
    _openid,
    userInfo,
    inviter
  } = event

  switch (op) {
    case 'visit':
      return visit()
      break;
    case 'updateUserInfo':
      return updateUserInfo()
      break;
    case 'updateNickname':
      return updateNickname()
      break;
    case 'getUserInfo':
      return getUserInfo()
      break;
    case 'getTop20Users':
      return getTop20Users()
      break;
    default:
      return getUserInfo()
  }

  async function visit() {
    if (_openid) {
      let result = await db.collection('User').where({
        _openid: _openid
      }).get()
      return result.data[0]
    } else {
      return randomUserVisit()
    }
  }
  async function updateUserInfo() {
    let result = await db.collection('User').where({
      _openid: wxContext.OPENID
    }).update({
      data: {
        nickname: userInfo.nickName,
        avatar: userInfo.avatarUrl,
        sex: userInfo.gender,
        city: userInfo.city,
        province: userInfo.province,
        gold: _.inc(5000),
      }
    })
    return result
  }
  async function updateNickname() {
    try {
      const result = await cloud.openapi.security.msgSecCheck({
        content: event.nickname
      })

      if (result && result.errCode.toString() === '87014') {
        return {
          code: 500,
          msg: '内容含有违法违规内容',
          data: result
        }
      } else {
        await db.collection("User").where({
          _openid: wxContext.OPENID
        }).update({
          data: {
            nickname: event.nickname
          }
        })
        return {
          code: 200,
          msg: 'ok',
          data: result
        }
      }
    } catch (err) {
      // 错误处理
      if (err.errCode.toString() === '87014') {
        return {
          code: 500,
          msg: '内容含有违法违规内容',
          data: err
        }
      }
      return {
        code: 502,
        msg: '调用security接口异常',
        data: err
      }
    }

  }
  async function randomUserVisit() {
    let result = await db.collection('User')
      .aggregate()
      .match({
        _openid: _.neq(wxContext.OPENID)
      })
      .sample({
        size: 1
      })
      .end()
    //增加记录
    await db.collection('Record').add({
      data: {
        _openid: wxContext.OPENID,
        createTime: db.serverDate(),
        content: {
          op: 'getIn',
          _openid: result.list[0]._openid
        }
      }
    })
    await db.collection('User').where({
      _openid: wxContext.OPENID,
    }).update({
      data: {
        active: _.inc(1),
      }
    })
    return result.list[0]
  }

  async function getUserInfo() {
    let result = await db.collection('User').where({
      _openid: wxContext.OPENID
    }).get()
    if (result.data.length <= 0) {
      return newUser()
    } else {

      let res = await db.collection('Treasure').where({
        _openid: wxContext.OPENID,
        amount: _.gt(0)
      }).get()
      let treasures = res.data
      let treasureAmount = 0
      for (let i = 0; i < treasures.length; i++) {
        let item = treasures[i]
        treasureAmount += item.amount
      }
      await db.collection('User').where({
        _openid: wxContext.OPENID
      }).update({
        data: {
          treasureAmount: treasureAmount
        }
      })
      result.data[0].treasureAmount = treasureAmount

      return result.data[0]
    }
  }
  async function newUser() {
    let result2 = await db.collection("User").add({
      data: {
        _openid: wxContext.OPENID,
        _unionid: wxContext.UNIONID,
        usertype: 1, //1-普通用户，0-管理员
        gold: 5000,
        treasureAmount: 0,
        dialTimes: 0,
        openBoxTimes: 0,
        loginDay: 0,
        active: 1,
        pet: {
          type: 1,
          life: 100,
          charm: 100
        },
        house: {
          type: 1,
          roomSum: 0,
          life: 100
        },
        register_time: db.serverDate()
      }
    })
    let result3 = await db.collection('User').where({
      _id: result2._id
    }).get()
    if (inviter) {
      await db.collection('UserRelationship').add({
        data: {
          inviter: inviter,
          invitee: result3.data[0]._openid,
          create_time: db.serverDate()
        }
      })
      await db.collection('User').where({
        _openid: inviter
      }).update({
        data: {
          gold: _.inc(500)
        }
      })
    }
    return result3.data[0]
  }

  async function getTop20Users() {
    let res = await db.collection('User').orderBy('gold', 'desc').limit(20).field({
      _openid: true,
      nickname: true,
      avatar: true,
      gold: true,
      treasureAmount: true,
    }).get()
    let list = res.data
    return list
  }
}